#include <X11/Xlib.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    Display *dpy;
    Window root, win;
    XEvent e;
    int s;
    unsigned int width, height, borderWidth, depth;
    XSetWindowAttributes attrs;

    dpy = XOpenDisplay(NULL);
    if (dpy == NULL) {
        printf("Cannot open display\n");
        return 1;
    }

    s = DefaultScreen(dpy);
    root = RootWindow(dpy, s);

    // 获取屏幕的宽度和高度
    int screen_width = DisplayWidth(dpy, s);
    int screen_height = DisplayHeight(dpy, s);

    // 设置窗口的宽度和高度
    width = 400;
    height = 300;

    // 设置窗口边框的宽度
    borderWidth = 1;

    // 设置窗口属性
    attrs.background_pixel = WhitePixel(dpy, s);
    attrs.border_pixel = BlackPixel(dpy, s);
    attrs.override_redirect = False; // 允许窗口管理器管理窗口

    // 创建窗口
    win = XCreateWindow(dpy, root, 0, 0, width, height, borderWidth, DefaultDepth(dpy, s), InputOutput, DefaultVisual(dpy, s), CWBackPixel | CWBorderPixel | CWOverrideRedirect, &attrs);

    // 计算窗口居中的位置
    int x = (screen_width - width) / 2;
    int y = (screen_height - height) / 2;
    XMoveWindow(dpy, win, x, y);

    // 设置窗口标题
    XStoreName(dpy, win, "Hello World!");

    // 显示窗口
    XMapWindow(dpy, win);

    // 事件循环
    while (1) {
        XNextEvent(dpy, &e);
        if (e.type == KeyPress) {
            break;
        }
    }

    // 关闭与X服务器的连接
    XCloseDisplay(dpy);
    return 0;
}